package org.dalmatian.common.translation.core;


import cn.hutool.core.collection.CollectionUtil;
import org.dalmatian.common.redis.utils.NamespaceCacheUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;


/**
 * @author zc
 */
@Component
@Slf4j
public class TranslationCache {

    public static final Map<String, TranslationInterface<?>> TRANSLATION_MAPPER = new ConcurrentHashMap<>();

    /**
     * 获取对象
     *
     * @param type
     * @param id
     * @param other
     * @return
     */
    public String get(String type, Object id, String other) {
        // 1. 检查本地缓存
        String value = String.valueOf(NamespaceCacheUtil.get(type, String.valueOf(id)));
        if (value != null) {
            return value;
        }else {
            NamespaceCacheUtil.configNamespace(type, 10000, 10, TimeUnit.MINUTES);
        }
        // 3. 实时翻译（兜底）
         String result =    translateInRealTime(type, id, other);
         if (result != null) {
             NamespaceCacheUtil.put(type, String.valueOf(id), result);
         }

        return  result;
    }

    private String translateInRealTime(String type, Object id, String other) {
        TranslationInterface<?> translator = TRANSLATION_MAPPER.get(type);
        if (translator == null) {
            return null;
        }
        try {
            return String.valueOf(translator.translation(id, other));
        } catch (Exception e) {
            log.error("Real-time translation failed: {}/{}", type, id, e);
            return null;
        }
    }

    public Map<String, String> batchFindByTypeAndCodes(String type, Set<String> ids, String other) {
        Map<String, Object> cacheMapAll = NamespaceCacheUtil.getAll(type);
        Map<String, String> result = new HashMap<>();
        List<String> keys = new ArrayList<>(ids);
        if (cacheMapAll == null) {
            NamespaceCacheUtil.configNamespace(type, 10000, 10, TimeUnit.MINUTES);
        } else {
            result.putAll(cacheMapAll.entrySet().stream()
                .collect(Collectors.toMap(
                    Map.Entry::getKey,
                    entry -> entry.getValue().toString()
                )));
            keys = ids.stream()
                .filter(element -> !cacheMapAll.containsKey(element)).toList();
            if (!CollectionUtil.isEmpty(keys)) {
                TranslationInterface<?> translator = TRANSLATION_MAPPER.get(type);
                if (translator != null) {
                    try {
                        Map<String, String> noCacheMap = translator.batchTranslation(
                            new ArrayList<>(keys), other);
                        // 調用接口
                        if (CollectionUtil.isNotEmpty(noCacheMap)) {
                            result.putAll(noCacheMap);
                            // 新增缓存
                            for (String key : noCacheMap.keySet()) {
                                NamespaceCacheUtil.put(type, key, noCacheMap.get(key));
                            }
                        }

                    } catch (Exception e) {
                        log.error("Real-time translation failed: {}/{}", type, keys, e);

                    }
                }

            }

        }
        return result;
    }


}